<template>
  <div class="user-reg-layout  home-main-box">

    <div class="reg-type-list">
      <div :class="type=='phone'?'type-item active webfont-Medium':'type-item webfont-Medium' " @click="changeRegType">手机号注册</div>
      <div :class="type=='email'?'type-item active webfont-Medium':'type-item webfont-Medium' " @click="changeRegType">邮箱注册</div>
    </div>
    <div class="user-reg-form form">

      <!-- 手机号注册开始 -->
      <register-phone v-if="type==='phone'" @changeType="changeType"></register-phone>
      <!-- 手机号注册结束 -->

      <!-- 邮箱注册开始 -->
      <registerEmail v-else  @changeType="changeType"></registerEmail>
      <!-- 邮箱注册结束 -->
    </div>
  </div>
</template>
<script>
import {
  userCode, // 验证图片验证码是否正确；
  createCode,
  emailRegister, // 邮箱验证码获取
  smsRegister, // 手机验证码获取
  register,
  findCampaignCount
} from '@/api/user.js'

import {
  isValidPhone,
  isValidEmail,
  isValidCode
} from '@/utils/validate'

import {
  getDefultPath
} from '@/utils/index.js'

import registerEmail from './registerEmail.vue'
import registerPhone from './registerPhone.vue'

let codeTime // 定时器
export default {
  components: {
    registerEmail,
    registerPhone
  },
  data() {
    // 手机密码一致验证
    var validatePhonePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.phoneFrom.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }

    // 邮箱密码一致验证
    var validateMailPass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.emailFrom.pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      phoneLoading: false,
      emailLoading: false,
      account: '',
      password: '',
      type: 'phone',
      code: undefined, // 验证码图片路径
      codeText: '获取验证码', // 验证码按钮文字
      countDown: 0, // 倒计时秒数
      agreeWith: false,
      phoneFrom: {
        user_phone: '',
        SMS: '',
        pwd2: '',
        pwd: '',
        code: ''
      },
      phoneRules: {
        user_phone: [{
          required: true,
          message: '请输入您的手机号码',
          trigger: 'blur'
        },
        {
          validator: isValidPhone,
          trigger: 'blur'
        }
        ],
        SMS: [{
          required: true,
          message: '请输入您的验证码',
          trigger: 'blur'
        }],
        pwd: [{
          required: true,
          message: '请输入您的密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }
        ],
        pwd2: [{
          required: true,
          validator: validatePhonePass2,
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '长度在8到16个字符',
          trigger: 'blur'
        }
        ],
        code: [{
          validator: isValidCode,
          trigger: 'blur'
        }]
      },
      emailFrom: {
        user_email: '',
        pwd: '',
        pwd2: '',
        code: ''
      },
      emailRules: {
        user_email: [{
          required: true,
          message: '请输入您的邮箱',
          trigger: 'blur'
        },
        {
          validator: isValidEmail,
          trigger: 'blur'
        }
        ],
        code: [{
          required: true,
          message: '请输入邮箱验证码',
          trigger: 'blur'
        }],
        pwd: [{
          required: true,
          message: '请输入您的密码',
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '请输入8到16位的密码',
          trigger: 'blur'
        }

        ],
        pwd2: [{
          required: true,
          validator: validateMailPass2,
          trigger: 'blur'
        },
        {
          min: 8,
          max: 16,
          message: '长度在8到16个字符',
          trigger: 'blur'
        }
        ]
      }
    }
  },
  mounted() {
    this.phoneFrom = {}
    this.emailFrom = {}
    // this.createCode()
  },
  methods: {
    changeType(data) {
      this.type = data
      this.$emit('changeType', data)
    },
    handleInput(e) {
      this.$forceUpdate()
    },
    intoClause(type) {
      const routeUrl = this.$router.resolve({
        path: '/account',
        query: {
          type
        }
      })
      window.open(routeUrl.href, '_blank')
    },

    // 获取验图片证码
    async createCode() {
      const res = await createCode()
      const blob = new Blob([res.data], {
        type: 'image/png'
      })
      const url = window.URL.createObjectURL(blob)
      this.code = url
    },

    // 发送手机或者邮箱验证码
    subPhoneEmailCode(type) {
      if (this.countDown > 0) return false

      if (type === 'phoneForm') {
        // 如果是请求发送手机验证码
        var MobileRegex = /^1[0-9]{10}$/
        const value = this.phoneFrom.user_phone
        if (!MobileRegex.test(value)) {
          this.$message.closeAll()
          this.$message.error('请输入正确的手机号码!')
        } else {
          this.getPhoneCode()
        }
        // 手机验证结束
      } else {
        // 如果是邮箱
        var mailRegex = /^\w*@[-a-zA-Z0-9]{1,20}\.[0-9a-z]{2,3}$/
        const value = this.emailFrom.user_email
        if (!mailRegex.test(value)) {
          this.$message.closeAll()
          this.$message.error('请输入正确的邮箱!')
        } else {
          this.getEmailCode()
        }
      }
    },

    // 邮箱验证码获取
    async getEmailCode() {
      const obj = {
        account: this.emailFrom.user_email,
        type: 'register' // 注册字段
      }
      const {
        data
      } = await emailRegister(obj)
      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
        // this.createCode()
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },
    // 手机验证码获取
    async getPhoneCode() {
      const obj = {
        account: this.phoneFrom.user_phone,
        type: 'register' // 注册字段
      }
      const {
        data
      } = await smsRegister({ ...obj
      })
      if (data.code !== 20000) {
        this.$message.closeAll()
        this.$message.error(data.message || '验证码发送失败,请重试!')
      } else {
        this.$message.closeAll()
        this.$message({
          message: data.message || '验证码发送成功',
          type: 'success'
        })
        this.runTime()
      }
    },

    // 验证码倒计时
    runTime() {
      const that = this
      this.countDown = 60
      codeTime = setInterval(() => {
        if (that.countDown <= 1) {
          clearInterval(codeTime)
          that.countDown = 0
          this.codeText = '获取验证码'
        } else {
          that.countDown -= 1
          this.codeText = this.countDown + 's'
        }
      }, 1000)
    },
    // 验证图片验证码是否正确
    async codeIsTrue(type) {
      const code = this.phoneFrom.code
      if (code < 4) {
        this.$message.closeAll()
        return false
      } else {
        const {
          data
        } = await userCode(code)
        if (data.code !== 20000) {
          this.$message.closeAll()
          this.$message.error(data.message || '验证码错误')
          /* this.createCode() */
          return false
        } else {
          return true
        }
      }
    },

    // 提交注册
    submitRegister(form) {
      const windowWidth = document.body.clientWidth
      if (windowWidth < 900) {
        this.$message.closeAll()
        this.$message.error('请在PC端提交')
        return false
      }
      this.phoneLoading = true
      this.emailLoading = true

      this.$refs[form].validate(async(valid) => {
        if (valid) {
          if (!this.agreeWith) {
            this.$message.closeAll()
            this.$message.error('请阅读并同意协议和政策')
            return false
          }
          let data = {}
          if (form.indexOf('phone') !== -1) {
            // const flag = await this.codeIsTrue()
            // if (!flag) return false
            this.account = this.phoneFrom.user_phone
            this.password = this.phoneFrom.pwd
            data = {
              mobile: this.phoneFrom.user_phone,
              pwd: this.phoneFrom.pwd,
              code: this.phoneFrom.SMS
            }
          } else {
            this.account = this.emailFrom.user_email
            this.password = this.emailFrom.pwd
            data = {
              email: this.emailFrom.user_email,
              pwd: this.emailFrom.pwd,
              code: this.emailFrom.code
            }
          }
          const res = await register({ ...data
          })
          this.phoneLoading = false
          this.emailLoading = false
          if (res.data.code !== 20000) {
            // 证明注册失败了
            this.$message.closeAll()
            this.$message.error(res.data.message || '注册失败，请稍后重试')
            /* this.createCode() */
          } else {
            this.$message.closeAll()
            this.$message({
              message: '注册成功，即将登录',
              type: 'success'
            })
            this.userLogin()
          }
        } else {
          this.phoneLoading = false
          this.emailLoading = false
          console.log('表单验证失败')
        }
      })
    },
    // 登录
    async userLogin() {
      let formlist = {}
      if (this.account.indexOf('@') !== -1) {
        formlist = {
          email: this.account,
          pwd: this.password
        }
      } else {
        formlist = {
          mobile: this.account,
          pwd: this.password
        }
      }
      const res = await this.$store.dispatch('user/login', formlist)
      const {
        data
      } = res

      if (data.code === 20000) {
        const userInfo = await this.$store.dispatch('user/getInfo')
        const path = getDefultPath(userInfo.roleName)
        this.$router.replace({
          path
        })
      } else {
        this.$message.error(data.message || '登录失败，请稍后重试')
      }
    },

    // 改变注册形式
    changeRegType() {
      if (this.type === 'phone') {
        this.$nextTick(function() {
          this.type = 'email'
          this.$forceUpdate()
        })
      } else {
        this.$nextTick(function() {
          this.type = 'phone'
          this.$forceUpdate()
        })
      }
    },
    // 去登录页面
    goLogin() {
      if (this.type == 'phone') {
        this.$refs['phoneForm'].resetFields()
      } else {
        this.$refs['emailForm'].resetFields()
      }
      this.$nextTick(function() {
        this.$emit('changeType', 'login')
      })
    }

  }
}
</script>

<style lang="scss" scoped="true">
  @import './style/form.scss';

  .type-list {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 0.32rem;
    line-height: 0.46rem;
    font-size: 0.24rem;

    .blue-btn {
      width: 48%;
    }

  }
</style>
